package cn.doitedu.kafka.interceptor;

import org.apache.kafka.clients.producer.ProducerInterceptor;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Map;

/***
 * @author hunter.d
 * @qq 657270652
 * @wx haitao-duan
 * @date 2020/11/11
 **/
public class ProducerInterceptorPrefix implements ProducerInterceptor<String,String> {
    private volatile long succeedCount;
    private volatile long failedCount;
    /**
     * 添加前缀
     * @param producerRecord
     * @return
     */
    @Override
    public ProducerRecord<String, String> onSend(ProducerRecord<String, String> producerRecord) {
        String value = producerRecord.value();
        String newValue = "prefix-" + value;

        return new ProducerRecord<String,String>(producerRecord.topic(),producerRecord.partition(),producerRecord.timestamp(),producerRecord.key(),newValue,producerRecord.headers());
    }

    /**
     *
     * @param recordMetadata
     * @param e
     */
    @Override
    public void onAcknowledgement(RecordMetadata recordMetadata, Exception e) {
        if(e == null){
            succeedCount ++;
        }else{
            failedCount ++;
        }

    }

    @Override
    public void close() {
        System.out.println("发送成功数： " + succeedCount);
        System.out.println("发送失败数： " + failedCount);
    }

    @Override
    public void configure(Map<String, ?> map) {

    }
}
